package com.ewzj.bigdata.mvp.presenter

import android.app.Application
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.ewzj.bigdata.app.config.AppKey
import com.ewzj.bigdata.app.utils.RxUtils
import com.ewzj.bigdata.mvp.contract.CitySelectorActivityContract
import com.ewzj.bigdata.mvp.contract.SearchActivityContract
import com.ewzj.bigdata.mvp.model.bean.CitygroupBean
import com.ewzj.bigdata.mvp.model.bean.HouseTypeBean
import com.ewzj.bigdata.mvp.model.reqbean.ReqAllSearch
import com.ewzj.bigdata.mvp.model.reqbean.ReqCityBean
import com.ewzj.bigdata.mvp.model.reqbean.ReqSearchCityBean
import com.ewzj.bigdata.mvp.model.rspbean.*
import com.ewzj.bigdata.mvp.ui.adapter.*
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.jess.arms.mvp.BasePresenter
import com.jess.arms.utils.DataHelper
import com.jess.arms.utils.UiUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.observables.GroupedObservable
import io.reactivex.schedulers.Schedulers
import me.jessyan.rxerrorhandler.core.RxErrorHandler
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber
import java.util.*
import javax.inject.Inject

/**
 * author:zhangjing
 * 作用:
 * return:
 */
class SearchActivityPresenter @Inject constructor(val mGson: Gson, val mErrorHandler: RxErrorHandler, val application: Application, view: SearchActivityContract.View, model: SearchActivityContract.Model) : BasePresenter<SearchActivityContract.Model, SearchActivityContract.View>(model, view) {
    val context=mRootView as AppCompatActivity
    val his = ArrayList<String>()
    val types = ArrayList<HouseTypeBean>()
    val homes = ArrayList<HomeBean>()
    val hisadapter=HotkeyAdapter(his)
    val typeadapter=TypeAdapter(types)
    val homeadapter=HomePageAdapter(homes)
    var page=1
    var keyword:String=""
    var hoursetype:String=""
    fun loadHisData(){
        val str = DataHelper.getStringSF(context, AppKey.SEARCH_HIS)
        if (!str.isNullOrEmpty()){
            val history = mGson.fromJson<List<String>>(str, object : TypeToken<List<String>>() {
            }.type)
            his.clear()
            his.addAll(history)
        }
        hisadapter.setOnItemChildClickListener { adapter, view, position ->
            mRootView.setSearchetString(adapter.data[position] as String)
            searchData(adapter.data[position] as String,hoursetype)
         }
        mRootView.initAdapter(hisadapter)
    }

    fun clearHis(){
        his.clear()
        hisadapter.notifyDataSetChanged()
    }

    fun inittype() {
        if (types.size != 0) {
            types.clear()
        }
        types.add(HouseTypeBean("新房", false))
        types.add(HouseTypeBean("二手房", true))
        types.add(HouseTypeBean("租房", false))
        types.add(HouseTypeBean("写字楼", false))
        types.add(HouseTypeBean("商铺", false))
        mRootView.inittypeAdapter(typeadapter)
    }

    fun searchData(keeword: String,housetype:String) {
        if (keeword.isNullOrEmpty()){
            UiUtils.SnackbarText("搜索内容不能为空")
            return
        }
        this.hoursetype=housetype
        this.keyword=keeword
        if (!his.contains(keeword)){
            his.add(keeword)
        }
        page=1
        mModel.searchHourse(searchBean(keeword,housetype)).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(object :ErrorHandleSubscriber<BaseData<BaseListData<HomeBean>>>(mErrorHandler){
                    override fun onNext(t: BaseData<BaseListData<HomeBean>>) {
                        page++
                        homes.clear()
                        homes.addAll(t.data!!.list)
                        homeadapter.setNewData(homes)
                        mRootView.switchAdapter(homeadapter as BaseQuickAdapter<Any, BaseViewHolder>,keyword)
                        if (t.data!!.list.size<AppKey.PAGE_NUM){
                            homeadapter.disableLoadMoreIfNotFullPage()
                        }
                    }

                })
    }
    fun initHomeAdapter(recyclerView: RecyclerView){
        homeadapter.setOnLoadMoreListener(object :BaseQuickAdapter.RequestLoadMoreListener{
            override fun onLoadMoreRequested() {
                loadmoreSearchdata()
            }

        },recyclerView)
    }
    fun loadmoreSearchdata() {
        mModel.searchHourse(searchBean(keyword,hoursetype)).compose(RxUtils.bindToLifecycle(mRootView))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate { if (homeadapter.isLoading){
                    homeadapter.loadMoreComplete()
                } }
                .subscribe( { t ->
                    run {
                        page++
                        homeadapter.addData(t.data!!.list)
                        if (t.data!!.list.size < AppKey.PAGE_NUM) {
                            homeadapter.loadMoreEnd()
                        }
                    }
                },{homeadapter.loadMoreFail()})
    }

    fun searchBean(keeword: String,housetype:String) :ReqAllSearch{
        var params=ReqAllSearch(page)
        params.words=keeword
        when(housetype){
            "新房"->params.groupId="1"
            "二手房"->params.groupId="8"
            "租房"->params.groupId="9"
            "写字楼"->params.words=keeword+" "+"写字楼"
            "商铺"->params.groupId=keeword+" "+"商铺"
        }
        return params
    }

    fun saveData(){
        var savestr=mGson.toJson(his)
        DataHelper.SetStringSF(context,AppKey.SEARCH_HIS,savestr)
    }
}